package org.ruixue.util;


import cn.rkylin.oms.common.dto.DBLog;
import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 日志工具类 实现org.apache.commons.logging.Log接口,向RabbitMQ发送日志，如果出现异常，则记录成本地日志
 */
@Component("logUtil")
public class LogUtil {

    private static final String sourType = "microservice-yiyouyayin";
    private static final Log log = LogFactory.getLog(LogUtil.class);
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void error(Object o) {
        try {
            DBLog log = (DBLog) o;
            log.setSourceType(sourType);
            log.setLogType("error");
            log.setOperTime(getCurrentDateStr());
        } catch (Exception ex) {
            log.info(o, ex);
        }
    }

    public void error(Object o, Throwable throwable) {
        try {
            DBLog log = (DBLog) o;
            log.setSourceType(sourType);
            log.setLogType("error");
            log.setOperTime(getCurrentDateStr());
            log.setThrowable(getStackTraceInfo(throwable));
        } catch (Exception ex) {
            log.info(o, ex);
        }
    }

    public void info(Object o) {
        try {
            DBLog log = (DBLog) o;
            log.setSourceType(sourType);
            log.setLogType("info");
            log.setOperTime(getCurrentDateStr());
        } catch (Exception ex) {
            log.info(o, ex);
        }
    }

    public void info(Object o, Throwable throwable) {
        try {
            DBLog log = (DBLog) o;
            log.setSourceType(sourType);
            log.setLogType("info");
            log.setOperTime(getCurrentDateStr());
            log.setThrowable(getStackTraceInfo(throwable));
        } catch (Exception ex) {
            log.info(o, ex);
        }
    }

    /**
     * 获取堆栈跟踪信息
     */
    private String getStackTraceInfo(Throwable throwable) {
        Map<String, String> tempMap = new LinkedHashMap<String, String>();
        StackTraceElement[] stackTraceElements = throwable.getStackTrace();
        for (int i = 0; i < stackTraceElements.length; i++) {
            tempMap.put("at" + i, stackTraceElements[i].toString());
        }
        return JSON.toJSONString(tempMap);
    }

    /***
     * 获取当前时间
     * @return
     */
    private String getCurrentDateStr(){
        Date date = new Date();
        String str = simpleDateFormat.format(date);
        return str;
    }
}
